from erpnext.controllers.taxes_and_totals import calculate_taxes_and_totals
from frappe.utils import cint, flt

original_get_current_tax_amount = calculate_taxes_and_totals.get_current_tax_amount

def custom_get_current_tax_amount(self, item, tax, item_tax_map):
    tax_rate = self._get_tax_rate(tax, item_tax_map)
    current_tax_amount = 0.0

    if tax.charge_type == "Actual":
        # distribute the tax amount proportionally to each item row
        actual = flt(tax.tax_amount, tax.precision("tax_amount"))

        if tax.get("is_tax_withholding_account") and item.meta.get_field("apply_tds"):
            if not item.get("apply_tds") or not self.doc.tax_withholding_net_total:
                current_tax_amount = 0.0
            else:
                current_tax_amount = item.net_amount * actual / self.doc.tax_withholding_net_total
        else:
            current_tax_amount = (
                item.net_amount * actual / self.doc.net_total if self.doc.net_total else 0.0
            )

    elif tax.charge_type == "On Net Total":
        # current_tax_amount = (tax_rate / 100.0) * item.net_amount
        if tax_rate == 0:
            current_tax_amount = 0.0
        else:
            current_tax_amount = flt(item.net_amount * (tax_rate / 100.0), tax.precision("tax_amount"))
            if tax.included_in_print_rate:
                tax_fraction = tax_rate / 100.0
                net_amount_without_tax = flt(item.amount/(1+tax_fraction), item.precision("net_amount"))
                if net_amount_without_tax==item.net_amount:
                    current_tax_amount=flt(item.amount-net_amount_without_tax, tax.precision("tax_amount"))
                
    elif tax.charge_type == "On Previous Row Amount":
        current_tax_amount = (tax_rate / 100.0) * self.doc.get("taxes")[
            cint(tax.row_id) - 1
        ].tax_amount_for_current_item
    elif tax.charge_type == "On Previous Row Total":
        current_tax_amount = (tax_rate / 100.0) * self.doc.get("taxes")[
            cint(tax.row_id) - 1
        ].grand_total_for_current_item
    elif tax.charge_type == "On Item Quantity":
        current_tax_amount = tax_rate * item.qty

    if not (self.doc.get("is_consolidated") or tax.get("dont_recompute_tax")):
        self.set_item_wise_tax(item, tax, tax_rate, current_tax_amount)

    return current_tax_amount


calculate_taxes_and_totals.get_current_tax_amount = custom_get_current_tax_amount